package com.renchunlin.sectetdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.fanjun.messagecenter.MessageCenter;
import com.fanjun.messagecenter.Msg;
import com.fanjun.messagecenter.annotion.MHanderReceiveTag;

public class MainActivity extends AppCompatActivity {

    private MyReceiver myReceiver;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注解方式注册订阅者
        MessageCenter.registMessageHandler(this);
        initView();
    }

    private void initView() {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);

        Button btnSendMsg = findViewById(R.id.btnSendMsg);
        EditText edContent = findViewById(R.id.edContent);
        btnSendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送到应用外的消息
                Msg outSideMsg = Msg.ini("outsideTag", edContent.getText().toString());
                outSideMsg.destination(Msg.APP_OUTSIDE);
                MessageCenter.sendMessage(outSideMsg);
            }
        });

        Button btnStopService = findViewById(R.id.btnStopService);
        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });
    }

    @MHanderReceiveTag("getMessage")
    void receiveOutside(Object obj) {

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("msg", "消息通知", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this, "msg")
                .setContentTitle("消息标题" + (String) obj)
                .setContentText("消息内容")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        manager.notify(2, notification);
    }
}